package com.rmb.system.aop;
import com.rmb.mart.entity.linxi.RmbSystemLoginLog;
import com.rmb.mart.entity.linxi.RmbSystemOperationLog;
import com.rmb.mart.entity.linxi.RmbSystemUser;
import com.rmb.mart.entity.linxi.util.IdWorker;
import com.rmb.system.aop.annotation.SystemLog;
import com.rmb.system.aop.utils.IpInfoUtil;
import com.rmb.system.aop.utils.ThreadPoolUtil;
import com.rmb.system.service.RmbSystemLoginLogService;
import com.rmb.system.service.RmbSystemOperationLogService;
import com.rmb.system.service.RmbSystemUserService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wan
 * @Title: SystemLogAspect
 * @Package aop
 * @Description: wan
 * @date 2021/1/229:05
 */
@Aspect
@Component
@Slf4j
public class SystemLogAspect {

    /**
     * 线程内部存储类
     */
    private static final ThreadLocal<Date> BEGIN_TIME_THREAD_LOCAL;

    static {
        BEGIN_TIME_THREAD_LOCAL = new NamedThreadLocal<>("ThreadLocal beginTime");
    }

    @Resource
    private RmbSystemOperationLogService operationLogService;

    @Resource
    private RmbSystemUserService rmbSystemUserService;

    @Resource
    private RmbSystemLoginLogService rmbSystemLoginLogService;

    @Resource
    private IpInfoUtil ipInfoUtil;

    @Resource
    private HttpServletRequest request;

    @Resource
    private IdWorker idWorker;

    /**
     * controller层切点
     */
    @Pointcut("@annotation(com.rmb.system.aop.annotation.SystemLog)")
    public void controllerAspect(){
    }

    /**
     * 登录controller层切点
     */
    @Pointcut("@annotation(com.rmb.system.aop.annotation.LoginLog)")
    public void loginAspect(){
    }

    /**
     * 记录操作日志开始时间
     */
    @Before("controllerAspect()")
    public void doBefore(){
        //线程绑定变量
        Date date = new Date();
        BEGIN_TIME_THREAD_LOCAL.set(date);
    }

    /**
     * 记录登录日志开始时间
     */
    @Before("loginAspect()")
    public void doLoginBefore(){
        //线程绑定变量
        Date date = new Date();
        BEGIN_TIME_THREAD_LOCAL.set(date);
    }

    /**
     * 无异常的操作,获取日志信息
     * @param joinPoint joinPoint对象
     */
    @AfterReturning("controllerAspect()")
    public void doAfterReturning(JoinPoint joinPoint){
        try {
            //获取操作描述
            String description = getControllerMethod(joinPoint).get("description").toString();
            //获取操作类型
            String type = getControllerMethod(joinPoint).get("type").toString();
            RmbSystemUser user = rmbSystemUserService.findByName("mark");
            RmbSystemOperationLog log = new RmbSystemOperationLog();
            //纳入对象
            log.setId(idWorker.nextId());
            log.setUsername(user.getName());
            log.setPhone(user.getPhone());
            log.setOperatingTime(new Date());
            log.setIpAddress(ipInfoUtil.getIpAddr(request));
            log.setRemark(user.getName()+"进行了"+type+",描述:"+description);
            log.setCreateTime(new Date());
            log.setUpdateTime(new Date());
            //调用添加方法
            saveSystemLogThread(log);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 无异常的操作,获取登录日志信息
     */
    @AfterReturning("loginAspect()")
    public void doLoginAfterReturning(){
        try {
            //查询到对象
            RmbSystemUser user = rmbSystemUserService.findByName("mark");
            //将信息纳入loginLog对象
            RmbSystemLoginLog loginLog = new RmbSystemLoginLog();
            loginLog.setId(idWorker.nextId());
            loginLog.setUsername(user.getName());
            loginLog.setPhone(user.getPhone());
            loginLog.setLoginTime(new Date());
            loginLog.setLoginStatus(user.getStatus());
            loginLog.setLoginStyle(1);
            loginLog.setLoginIp(ipInfoUtil.getIpAddr(request));
            loginLog.setLoginCity("上海");
            loginLog.setCreateTime(new Date());
            loginLog.setUpdateTime(new Date());
            //调用添加登录日志
            saveLoginLogThread(loginLog);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 保存日志至数据库
     * @param log 对象
     */
    private void saveSystemLogThread(RmbSystemOperationLog log){
        //线程执性添加操作
        Runnable runnable = () -> operationLogService.insert(log);
        ThreadPoolUtil.getPool().execute(runnable);
        //清除线程
        BEGIN_TIME_THREAD_LOCAL.remove();
    }

    /**
     * 保存登录日志至数据库
     * @param loginLog 对象
     */
    private void saveLoginLogThread(RmbSystemLoginLog loginLog){
        //线程执性添加操作
        Runnable runnable = () -> rmbSystemLoginLogService.insert(loginLog);
        ThreadPoolUtil.getPool().execute(runnable);
        //清除线程
        BEGIN_TIME_THREAD_LOCAL.remove();
    }


    /**
     * 获取注解中对方法的描述
     * @param joinPoint 获取类
     * @return map
     */
    public static Map<String,Object> getControllerMethod(JoinPoint joinPoint) throws ClassNotFoundException {
        Map<String,Object> map = new HashMap<>(16);
        /*获取他们的目标对象信息*/
        String targetName = joinPoint.getTarget().getClass().getName();
        /*(signature是信号,标识的意思):获取被增强的方法相关信息*/
        String methodName = joinPoint.getSignature().getName();
        /*获取带参方法的参数*/
        Object[] args = joinPoint.getArgs();
        Class<?> aClass = Class.forName(targetName);
        Method[] methods = aClass.getMethods();

        String description;
        String type;
        //得到的方法集合进行效验
        for (Method method : methods) {
            if(!method.getName().equals(methodName)){
                continue;
            }
            //通过反射来得到这个类对象
            Class<?>[] classes = method.getParameterTypes();
            if(classes.length != args.length){
                //比较方法中参数个数与切点获取个数是否相同
                continue;
            }
            //获取指定类型的注解
            description = method.getAnnotation(SystemLog.class).description();
            type = method.getAnnotation(SystemLog.class).type().getValue();
            map.put("description",description);
            map.put("type",type);
        }
        return map;
    }
}
